import React, { Component } from 'react';
import ReactDom from 'react-dom';
import util from "@/common/util";
import ReactSwiper from 'reactjs-swiper';
import jquery from 'jquery';


class Card extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tipList: [],
            images: [
                //里面的数据参数是固定的 image代表src link代表a链接 title代表图片说明
                //{ image: '', title: '', link: '' }，{ image: '', title: '', link: '' }
            ],
            bankList: [],
            cardList: []
        }
    }

    async sendcode() {
        var wechatcode = util.getQuery().code;
        let res = await util.rjax({
            url: '/wxAuthenticate/getOpenId?code=' + wechatcode,
            type: 'post',
        }).catch((res) => {
            console.log("catch:" + res)
        })

        if (res) {
            console.log("if(res):" + res)
            sessionStorage.setItem("openid", res.data.openId)
        }
    }

    componentDidMount() {
        if (util.getQuery().code) {
            var openid = sessionStorage.getItem("openid")
            if (!openid || openid === 'null') {
                this.sendcode()
            }
        }
        else {
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxeaccffdd3826280c&redirect_uri=http%3a%2f%2fwww.rongsue.com%2fwechat%2fcard.html&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`
        }

        let getconfig = async function () {
            let res = await util.rjax({
                url: "/wx/getwx?url=" + encodeURIComponent(window.location.href.split('#')[0]),
                type: "POST"
            })

            if (res) {
                wx.config({
                    debug: false,
                    appId: 'wxeaccffdd3826280c', // 必填，公众号的唯一标识
                    timestamp: parseInt(res.data.timestamp),// 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr,// 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']// 必填，需要使用的JS接口列表
                })
            }
        }
        getconfig()

        wx.ready(function () {
            //朋友圈
            wx.onMenuShareTimeline({// 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '各大银行信用卡免费办理', // 分享标题
                link: 'http://www.rongsue.com/wechat/card.html', // 分享链接
                imgUrl: 'http://img0.rongsue.com/FtcG05DG5SyLU9y2jg_bSmqwHzvA',
                success: function (res) {
                },
                cancel: function (res) {
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });

            //朋友
            wx.onMenuShareAppMessage({//获取“分享给朋友”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '各大银行信用卡免费办理', // 分享标题
                desc: '各大银行信用卡免费办理', // 分享描述
                link: 'http://www.rongsue.com/wechat/card.html', // 分享链接
                imgUrl: 'http://img0.rongsue.com/FtcG05DG5SyLU9y2jg_bSmqwHzvA', // 分享图标
                type: '', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        });

        this.getBannerList()
        this.getTipList()
        this.getBankList()
        this.getCardList()
        setInterval(this.noticeUp, 2000);
    }

    async  getBannerList() {
        let res = await util.rjax({
            url: '/banner/list?type=0',
            type: 'get',
        })
        this.setState({ images: res.data.rows })
    }

    async  getTipList() {
        let res = await util.rjax({
            url: '/banner/list?type=1',
            type: 'get',
        })
        this.setState({ tipList: res.data.rows });
    }

    async getBankList() {

        let res = await util.rjax({
            url: '/bank/list',
            type: 'get',
        })
        if (res.data.length > 4) {
            jquery(".moreBank").show()
            this.setState({ bankList: res.data.slice(0, 3) });
        } else {
            jquery(".moreBank").hide()
            this.setState({ bankList: res.data });
        }
    }

    async  getCardList() {
        let res = await util.rjax({
            url: '/card/list',
            type: 'get',
        })
        this.setState({ cardList: res.data.rows });
    }

    noticeUp() {
        jquery(".noticeul").animate({
            marginTop: '-35px'
        }, 2000, function () {
            jquery(this).css({ marginTop: "0" }).find(":first").appendTo(this);
        })
    }

    render() {
        // https://www.npmjs.com/package/reactjs-swiper
        // 文档是错的，注入swiper设置应该使用 options={}

        // swiper设置,版本3.4.2
        // http://3.swiper.com.cn/api/index.html

        const swiperOptions = {
            preloadImages: true,
            autoplay: 5000,
            autoplayDisableOnInteraction: false,
            spaceBetween: 0
            // direction: 'vertical'
        };
        let hotBanks = this.state.bankList.map((item, index) => {
            return (
                <li data-id={item.id} key={index}>
                    <a href={"./cardlist.html?id=" + item.id}>
                        <span>{}</span>
                        <img src={item.logo} alt="" />
                        <p>{item.name}</p>
                    </a>
                </li>
            )
        })
        let tips = this.state.tipList.map((item, index) => {
            return (
                <li key={index}>
                    <a href="">{item.title}</a>
                </li>
            )
        })
        return (
            <div>
                <div id="card">
                    <ReactSwiper options={swiperOptions} showPagination items={this.state.images} />

                    {/* tips */}
                    <div className="tips">
                        <span className="tipvol">
                            <img src="/assets/wechat/vol.png" alt="" />
                        </span>
                        <div className="notice">
                            <ul className="noticeul">
                                {tips}
                            </ul>
                        </div>
                    </div>

                    {/* banks */}
                    <div className="banks">
                        <h4>热门银行</h4>
                        <ul>
                            {hotBanks}
                            <li className="moreBank" >
                                <a href="./banklist.html">
                                    <span>
                                        <i className="dot"></i>
                                        <i className="dot"></i>
                                        <i className="dot"></i>
                                    </span>
                                    <p>更多银行</p>
                                </a>
                            </li>
                        </ul>
                    </div>

                    {/* cardcomm */}
                    <div className="cardcomm">
                        <h4>热门银行卡推荐</h4>
                        <ul className="cardlist">
                            {this.state.cardList.map((item, index) =>
                                <li key={index}>
                                    <h5>{item.name}</h5>
                                    <img src={item.image} alt="" />
                                    <div className="carddel">
                                        {/* <p className="cardlimit">
                                            <span>取现额度&nbsp;<i>{item.position}</i>&nbsp;元</span><br />
                                            <span>免息期&nbsp;<i className="freetime">{item.interestFree}个月</i>&nbsp;</span>
                                        </p> */}
                                        <p className="cardintr">简单介绍:{item.summary}</p>
                                        <p className="applybtn"><a href={item.link}>点击办理</a></p>
                                    </div>
                                </li>
                            )}
                        </ul>
                    </div>
                </div>
            </div>
        )
    }
}
ReactDom.render(<Card />, document.getElementById("app"));